<?php
/*
 * Copyright (c) 2013 Eugene Kuzmenko
 *
 * Permission  is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in  the Software without restriction, including without limitation the rights
 * to  use,  copy,  modify,  merge, publish, distribute, sublicense, and/or sell
 * copies  of  the  Software,  and  to  permit  persons  to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The  above  copyright  notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE  SOFTWARE  IS  PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED,  INCLUDING  BUT  NOT  LIMITED  TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS  FOR  A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS  OR  COPYRIGHT  HOLDERS  BE  LIABLE  FOR  ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * For more information, see <http://www.aljey.com>.
 */

namespace Al\Validation\Lib;

use Al\Validation\Exception\InvalidValidatorAdapterException,
    Al\Validation\Exception\UnknownValidatorAdapterException,
    Al\Validation\Exception\ValidatorException,
    Al\Core\Lib\Service;

/**
 * Provides validation of arbitrary class instances.
 *
 * @author Eugene Kuzmenko <mail@aljey.com>
 */
class Validator {

  /**
   * @var array A collection of instantiated validator adapters.
   */
  private $adapters = array();

  /**
   * Returns a validator adapter instance.
   *
   * @param string $name A name of a validator adapter.
   * @return AbstractValidatorAdapter A validator adapter instance.
   * @throws UnknownValidatorAdapterException
   * @throws InvalidValidatorAdapterException
   */
  public function getAdapter($name) {
    if (!isset($this->adapters[$name])) {
      if (!($config = Service::get(
          "config.plugins.Al\\Validation.adapter.$name"))) {
        if (!is_file(Service::get('autoload')->find($name))) {
          throw new UnknownValidatorAdapterException($name);
        }
        $config = $name;
      }
      $this->adapters[$name] = new $config;
      if (!($this->adapters[$name] instanceof AbstractValidatorAdapter)) {
        unset($this->adapters[$name]);
        throw new InvalidValidatorAdapterException($name);
      }
    }
    return $this->adapters[$name];
  }

  /**
   * Validates any given object.
   *
   * @param $object mixed Any arbitrary class instance.
   * @return array A status array.
   * @throws ValidatorException
   */
  public function validate($object) {
    if (!($config = Service::get('config.validation.' . get_class($object)))) {
      throw new ValidatorException(
        'No validation configuration has been found for the given object.');
    }
    $reflect = new \ReflectionClass($object);
    $props = $reflect->getProperties(\ReflectionProperty::IS_PUBLIC);
    $meths = $reflect->getMethods(\ReflectionMethod::IS_PUBLIC);
    array_walk($props, function (&$val) {
      $val = $val->name;
    });
    array_walk($meths, function (&$val) {
      $val = $val->name;
    });
    $response = array('valid' => true, 'errors' => array());
    foreach ($config as $key => $field) {
      $has = false;
      $value = null;
      foreach ($props as $prop) {
        if (strcasecmp($key, $prop) === 0) {
          $has = true;
          $value = $object->$prop;
          break;
        }
      }
      if (!$has) {
        foreach ($meths as $method) {
          if ((strcasecmp($key, $method) === 0) ||
              (strcasecmp("get$key", $method) === 0) ||
              (strcasecmp("is$key", $method) === 0)) {
            $has = true;
            $value = call_user_func(array($object, $method));
            break;
          }
        }
      }
      if (!$has) {
        throw new ValidatorException('The provided object does not have a field'
          . " named $key.");
      }
      if (!is_array($field)) {
        $field = array('adapter' => $field);
      }
      if (!isset($field['adapter'])) {
        throw new ValidatorException('No validation adapter is configured for '
          . "the field $key.");
      }
      $adapter = $this->getAdapter($field['adapter']);
      if ((is_null($value) || ($value === '')) &&
          !(isset($field['allow_blank']) ? (bool)$field['allow_blank'] :
          $adapter->getAllowBlank())) {
        $response['valid'] = false;
        $response['errors'][$key] = isset($field['required_message']) ?
          (string)$field['required_message'] : $adapter->getRequiredMessage();
        continue;
      }
      if (!$adapter->validate($value, (isset($field['options']) &&
          is_array($field['options'])) ? $field['options'] : array())) {
        $response['valid'] = false;
        $response['errors'][$key] = isset($field['invalid_message']) ?
          (string)$field['invalid_message'] : $adapter->getInvalidMessage();
      }
    }
    return $response;
  }

}